// app.js
App({
  onLaunch(e) {

  },
  // api地址
  api_root: '',

  // app 静默登陆
  appSetLogin(data = {}, fun) {
    const _this = this
    wx.login({
      success (res) {
        if (res.code) {
          _this._post_form('/api/auth-login', {
            code: res.code,
            ...data
          }, (res)=>{
            if(res.code === 200){
              wx.setStorageSync('token', res.data.token)
              fun && fun()
            }
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })
  },
  // 检测是否登录
  appLoginOk(callBack, isAjaxLogin = false) {
    const _this = this
    _this._post_form('/api/get-is-login', {}, (res)=>{
      if(res.code === 200){
        if(!res.data){
          _this.appSetLogin({},()=>{
            callBack()
          })
        } else {
          callBack()
        }
      }
    })
    
  },
  copy: function (text) {
    
   wx.setClipboardData({
     data: text,
     success: function (res) {
       wx.getClipboardData({
         //这个api是把拿到的数据放到电脑系统中的
         success: function (res) {
           wx.showToast({
            title: '已复制',
            icon: 'none',
            duration: 1000
          })
          
         }
       })
     }
   })
 },

  /**
   * post提交
   */
  _post_form(url, data, success, fail, complete, isShowNavBarLoading = true) {
    let _this = this;
    isShowNavBarLoading || true;
    if (isShowNavBarLoading == true) {
      wx.showNavigationBarLoading();
      wx.showLoading({
        mask: true,
        title: '正在请求...',
      })
    }
    wx.request({
      url: _this.api_root + url,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'token': wx.getStorageSync('token') || ''
      },
      timeout: 600000,
      method: 'POST',
      data: data,
      success(res) {
        if (res.statusCode !== 200 || typeof res.data !== 'object') {
          _this.showError('网络请求出错');
          return false;
        } else if(res.data.code === 4000){
          // 登录失效
          wx.removeStorage({
            key:'token'
          })

          return false
        }else if (
          res.data.code !== 200 && 
          res.data.code !== 4000
        ) {
          _this.showError(res.data.message, () => {
            fail && fail(res);
          });
          return false;
        }
        success && success(res.data);
      },
      fail(res) {
        _this.showError(res.errMsg, () => {
          fail && fail(res);
        });
      },
      complete(res) {
        wx.hideNavigationBarLoading();
        wx.hideLoading();
        complete && complete(res);
      }
    });

  },
  /**
   * 显示失败提示框
   */
  showError(msg, callback) {
    wx.showModal({
      title: '提示',
      content: msg,
      showCancel: false,
      success(res) {
        // callback && (setTimeout(() => {
        //   callback();
        // }, 1500));
        callback && callback();
      }
    });
  },

})